"""
@Time ： 2025/8/6 15:28
@Auth ： zh
@File ：deal_method.py
"""
import requests
import base_data


# 用于提交项目前的清单和工料机的批量处理 此处主要是方法
class deal_method:

    # 获取树结构id
    @staticmethod
    def get_tree_id(quotaId):
        test_data = {
            "quotaId": quotaId
        }

        try:
            # 发送POST请求
            response = requests.post(
                url=base_data.tree_url,
                json=test_data,
                headers=base_data.headers,
                timeout=10
            )

            # 检查请求是否成功
            if response.status_code == 200:
                response_data = response.json()
                print("API响应数据：", response_data)  # 打印完整响应（可选）

                # 提取所有三级项目的id
                ids = []
                if "data" in response_data and "children" in response_data["data"]:
                    for first_level in response_data["data"]["children"]:
                        if "children" in first_level and first_level["children"]:
                            for second_level in first_level["children"]:
                                if "id" in second_level:
                                    ids.append(second_level["id"])

                print("提取的ID列表：", ids)
                print("提取id列表的长度：", len(ids))
                return ids
            else:
                print(f"请求失败，状态码：{response.status_code}，错误信息：{response.text}")
                return None

        except requests.exceptions.RequestException as e:
            print(f"请求发生异常：{e}")
            return None

    # 获取科目id
    @staticmethod
    def get_subject_id():
        subject_data = {
            "templateId": "1",
            "categoryId": "6815877656978919424",
            "keyword": ""
        }
        try:
            response = requests.post(
                url=base_data.subject_url,
                json=subject_data,
                headers=base_data.headers,
                timeout=10
            )

            if response.status_code == 200:
                response_data = response.json()
                # 获取第一个id（data数组的第一个元素的id）
                if response_data.get("data") and isinstance(response_data["data"], list) and len(
                        response_data["data"]) > 0:
                    first_id = response_data["data"][0]['children'][0]["id"]
                    print("第一个ID值：", first_id)
                    return first_id
                else:
                    print("响应中没有有效的数据")
                    return None
            else:
                print(f"请求失败，状态码：{response.status_code}")
                return None

        except requests.exceptions.RequestException as e:
            print(f"请求异常：{e}")
            return None

    print(get_subject_id())

    # 获取未处理清单的所有id
    @staticmethod
    def get_deal_billTree(quotaId, structureId):  # quotaId, structureId
        bill_data = {
            "quotaId": quotaId,
            "structureId": structureId,
            "queryType": 2
        }
        try:
            response = requests.post(
                url=base_data.for_deal_bill,
                json=bill_data,
                headers=base_data.headers,
                timeout=10
            )

            if response.status_code == 200:
                response_data = response.json()
                ids = []

                # 递归提取所有children下的id
                def extract_ids(node):
                    if isinstance(node, dict):
                        if "id" in node and node.get("billNode") is True:  # 仅提取billNode为True的id
                            ids.append(node["id"])
                        if "children" in node and node["children"]:
                            for child in node["children"]:
                                extract_ids(child)
                    elif isinstance(node, list):
                        for item in node:
                            extract_ids(item)

                if "data" in response_data:
                    for item in response_data["data"]:
                        extract_ids(item)

                # print("提取的ID列表：", ids)
                # print("长度为：", len(ids))
                return ids
            else:
                print(f"请求失败，状态码：{response.status_code}")
                return []

        except Exception as e:
            print(f"发生异常：{e}")
            return []

    @staticmethod
    def get_CategoryMaterialItemTree(quotaId):
        """
        获取分类材料项树，并提取特定节点ID
        条件：children为null且name为"418"的节点
        """
        test_data = {
            "quotaId": quotaId,
        }

        try:
            # 发送POST请求
            response = requests.post(
                url=base_data.CategoryMaterialItemTree_url,
                json=test_data,
                headers=base_data.headers,
                timeout=10
            )

            # 检查请求是否成功
            if response.status_code == 200:
                response_data = response.json()
                print("API响应数据：", response_data)  # 打印完整响应（可选）

                # 提取特定ID
                target_id = None

                def find_target_id(node):
                    nonlocal target_id
                    if isinstance(node, dict):
                        # 检查是否符合条件
                        if node.get("children") is None and node.get("name") == "418":
                            target_id = node.get("id")
                            return  # 找到后立即返回
                        # 如果有children继续遍历
                        if "children" in node and node["children"]:
                            for child in node["children"]:
                                find_target_id(child)
                    elif isinstance(node, list):
                        for item in node:
                            find_target_id(item)

                # 从data开始遍历
                if "data" in response_data:
                    find_target_id(response_data["data"])

                if target_id:
                    print(f"找到的目标ID: {target_id}")
                    return target_id
                else:
                    print("未找到符合条件的节点ID")
                    return None

            else:
                print(f"请求失败，状态码：{response.status_code}，错误信息：{response.text}")
                return None

        except requests.exceptions.RequestException as e:
            print(f"请求发生异常：{e}")
            return None

    # 获取未处理的材料
    @staticmethod
    def get_material_ids(quotaId,structureId):
        """
        获取未处理材料的ID列表
        :param structureId: 结构树id
        :param quotaId: 项目ID
        :return: 材料ID列表，如果失败返回None
        """
        test_data = {
            "quotaId": quotaId,
            "structureId": structureId,
            "queryType": 2,
            "materialItemId": "",
            "keyword": "",
            "pageNumber": 1,
            "pageSize": 1000
        }

        try:
            # 发送POST请求
            response = requests.post(
                url=base_data.material_url,
                json=test_data,
                headers=base_data.headers,
                timeout=10
            )

            # 检查请求是否成功
            if response.status_code == 200:
                response_data = response.json()
                print("API响应数据：", response_data)  # 打印完整响应（可选）

                # 提取所有id值
                id_list = []
                if response_data.get("code") == 200:
                    data = response_data.get("data", {})
                    material_list = data.get("list", [])

                    for material in material_list:
                        if "id" in material:
                            id_list.append(material["id"])

                print("提取的ID列表：", id_list)
                return id_list
            else:
                print(f"请求失败，状态码：{response.status_code}，错误信息：{response.text}")
                return None

        except requests.exceptions.RequestException as e:
            print(f"请求发生异常：{e}")
            return None

